#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#include <filesystem>
#include <string>
#include <iostream>
using namespace std;
namespace fs = std::filesystem;
int split_in_two(fs::directory_entry inFile)
{
    // 输出目录
    string out_dir = inFile.path().parent_path().string() + "\\out\\";
    // 如果输出目录不存在，则创建它
    if (!fs::exists(out_dir)) {
        if (!fs::create_directories(out_dir)) {
            std::cerr << "Failed to create directory: " << out_dir << std::endl;
            return -1;
        }
    }    
    // 加载图像
    int width, height, channels;
    unsigned char *image_data = stbi_load(inFile.path().string().c_str(), &width, &height, &channels, 0);

    if (!image_data)
    {
        std::cerr << "Failed to load image." << std::endl;
        return -1;
    }

    // 分割图像为两部分
    int half_height = height / 2;
    unsigned char *top_half_data = new unsigned char[width * half_height * channels];
    unsigned char *bottom_half_data = new unsigned char[width * half_height * channels];

    // 复制上半部图像数据
    for (int i = 0; i < half_height; ++i)
    {
        memcpy(top_half_data + i * width * channels,
               image_data + i * width * channels,
               width * channels);
    }

    // 复制下半部图像数据
    for (int i = 0; i < half_height; ++i)
    {
        memcpy(bottom_half_data + i * width * channels,
               image_data + (i + half_height) * width * channels,
               width * channels);
    }

    // 保存分割后的图像
    string top_half_name = out_dir + inFile.path().stem().string() + "_1.jpg";
    string bottom_half_name = out_dir + inFile.path().stem().string() + "_2.jpg";
    stbi_write_jpg(top_half_name.c_str(), width, half_height, channels, top_half_data, 100); // 100 is the quality level
    stbi_write_jpg(bottom_half_name.c_str(), width, half_height, channels, bottom_half_data, 100);

    // 清理资源
    delete[] top_half_data;
    delete[] bottom_half_data;
    stbi_image_free(image_data);
    std::cout << inFile.path().filename() << " Images saved successfully." << std::endl;
    return 0;
}
int main()
{

    // 当前目录路径
    fs::path current_path = fs::current_path();
    cout << current_path.string() << endl;

    // 遍历当前目录下的所有文件
    for (const auto &entry : fs::directory_iterator(current_path))
    {
        // 检查文件是否为常规文件且扩展名为.jpg或.JPG
        if (entry.is_regular_file() && (entry.path().extension() == ".jpg" || entry.path().extension() == ".JPG"))
        {
            std::string filename = entry.path().string();
            // cout << filename << endl;
            // cout << entry.path().filename() << endl;
            // cout << entry.path().parent_path() << endl;
            // cout << entry.path().extension() << endl;
            split_in_two(entry);
        }
    }
    system("pause");
    return 0;
}